package com.google.code.ccr4j.extensions;

import org.apache.xmlbeans.XmlObject;

import com.google.code.ccr4j.ActorType;
import com.google.code.ccr4j.CommunicationType;

/**
 * Static helpers called by XMLBeans to implement the TelephoneHelper extension interface
 * @see TelephoneHelper
 * @author aeagle
 *
 */
public class TelephoneHelperImpl { // sort of implements TelephoneHelper {

    public static String getHomePhone(XmlObject xmlObject) {
        checkType(xmlObject);
        return getPhone((ActorType)xmlObject, TelephoneHelper.HOME_PHONE);
    }

    public static String getWorkPhone(XmlObject xmlObject) {
        checkType(xmlObject);
        return getPhone((ActorType)xmlObject, TelephoneHelper.WORK_PHONE);
    }

    public static void setHomePhone(XmlObject xmlObject, String phone) {
        checkType(xmlObject);
        setPhone(phone, (ActorType)xmlObject, TelephoneHelper.HOME_PHONE);
    }
    
    public static void setWorkPhone(XmlObject xmlObject, String phone) {
        checkType(xmlObject);
        setPhone(phone, (ActorType)xmlObject, TelephoneHelper.WORK_PHONE);
    }
    
    private static void checkType(XmlObject xmlObject) {
        if (!(xmlObject instanceof ActorType)) {
            throw new IllegalArgumentException("Can only handle ActorType, not " + xmlObject.getClass().getName());
        }
    }
    
    private static String getPhone(ActorType actor, String type) {
    	CommunicationType phone = findPhone(actor, type);        

        if (phone != null) {
            return phone.getValue();
        }
        // didn't find a phone of this type, so give a phone with no type
        for (CommunicationType comm : actor.getTelephoneList()) {
            if (!comm.isSetType()) {
                return comm.getValue();
            }
        }
    
        // didn't find it...
        return null;
    }

    private static CommunicationType findPhone(ActorType actor, String type) {
        for (CommunicationType comm : actor.getTelephoneList()) {
            if (comm.isSetType()) {
                if (type.equals(comm.getType().getText())) {
                    return comm;
                }
            }
        }
        return null;
    }
    
    private static void setPhone(String phone, ActorType actor, String phoneType) {
        CommunicationType existingPhone = findPhone(actor, phoneType);
        if (existingPhone != null) {
            existingPhone.setValue(phone);
        } else {
            CommunicationType commType = CommunicationType.Factory.newInstance();
            commType.addNewType().setText(phoneType);
            commType.setValue(phone);
            actor.getTelephoneList().add(commType);            
        }
    }
}
